<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<c:set value="<%=request.getContextPath()%>" var="ctx"></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="关键字台">
    <meta name="description" content="描述"> 
    <link href="${ctx}/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="${ctx}/css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <link href="${ctx}/css/animate.css" rel="stylesheet">
    <link href="${ctx}/css/style.css?v=4.1.0" rel="stylesheet">
    <link href="${ctx}/css/plugins/dataTables/dataTables.bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="${ctx}/css/plugins/toastr/toastr.min.css">

	<title>卡券管理</title>


</head>
<body class="gray-bg">
	<div class="wrapper wrapper-content animated fadeInRight">
	<div class="row">
		<div class="col-sm-12">
			<div class="ibox">
				<div class="ibox-title" style="min-height: 60px;">
					<div class="row">
                           <div class="col-sm-10">
                                <h3>${gift.gift_name } 卡券管理</h3>
                           </div>
                           <div class="col-sm-2">
                                <div class="ibox-tools">
									<a class="btn btn-success btn-block" style="color:#fff" href="${ctx}/giftManage/listGift">
									返回积分礼品列表
									</a>
                                </div>
                            </div>
                        </div>
				</div>
				<div class="ibox-content">
					
						<form class="form-inline pull-right" id="addCouponForm">
							<div class="form-group">
								<label class=" control-label">卡券：</label> <input type="hidden"
									name="id" value="${giftId}"> <input
									type="text" name="couponname" class="form-control" maxlength="50"
									placeholder="请输入卡券"><input
									type="text" name="pwd" class="form-control" maxlength="50"
									placeholder="请输入卡密">
							</div>
							<button class="btn btn-success" id="addCoupon" type="button">添加</button>
						</form>
						<button id="adds" class="btn btn-success" data-toggle="modal" data-cid="${giftId}">批量添加</button>
					

					<hr>
					<table
						class="table table-striped table-bordered table-hover dataTables-example text-center">

						<thead>
							<tr>
								<th class="text-center">序号</th>
								<th class="text-center">卡券</th>
								<th class="text-center">卡密</th>
								<th class="text-center">状态</th>
								<th class="text-center">添加时间</th>
								<th class="text-center">领取时间</th>
								<th class="text-center">操作</th>
							</tr>
						</thead>
						<tbody>
							<!-- 
							<c:forEach items="${cpList}" var="cp" varStatus="status">
								<tr class="gradeX">
									<td class="center">${status.index+1}</td>
									<td class="center">${cp.coupon}</td>
									<td class="center"><c:if test="${cp.status == 0}">
											未领取
										</c:if> <c:if test="${cp.status == 1}">
											已领取
										</c:if></td>
									<td class="center"><fmt:formatDate
											value="${cp.create_time}" pattern="yyyy-MM-dd HH:mm:ss" /></td>

									<td class="center"><fmt:formatDate value="${cp.draw_time}"
											pattern="yyyy-MM-dd HH:mm:ss" /></td>

									<td class="center">
									<c:if test="${cp.status == 1}">
									<button class="btn btn-danger" onclick="showNoDelModal();">删除</button>
									</c:if>
									<c:if test="${cp.status == 0}">
									<button class="btn btn-danger" onclick="showDelModal('${cp.id}');">删除</button>
									</c:if>
									</td>
								</tr>
							</c:forEach>
							 -->
						</tbody>
					</table>
					</div>
				</div>
			</div>
		</div>
		</div>
	</div>

	<div class="modal fade" id="delModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">提示</h4>
				</div>
				<div class="modal-body" id="alertDel">确定删除该条信息吗？</div>
				<div class="modal-footer">
					<form method="post" id="delCoupon" class="form-horizontal">
						<input type="hidden" name="id" id="delCouponId" />
						<input type="hidden" name="gift_id"  value="${giftId}"/>
						<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
						<button type="button" class="btn btn-primary"  id="delBtn">删除</button>
					</form>
				</div>
			</div>
		</div>
	</div>
	<div class="modal fade" id="noDelModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">提示</h4>
				</div>
				<div class="modal-body" id="alertDel">已领取的卡券不能被删除！</div>
				<div class="modal-footer">
					<form method="post" id="delCoupon" class="form-horizontal">
						<input type="hidden" name="id"  value=""/>
						<button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
					</form>
				</div>
			</div>
		</div>
	</div>
	<div class="modal fade" id="batchAdd" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
		<form class="form-horizontal" id="batchAddCoupon" method="post" action="couponBatchAdd" enctype="multipart/form-data">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">批量导入卡券</h4>
				</div>
					<div class="modal-body" id="alertDel">
						<input type="hidden" name="id" id="addCouponId" value="${giftId}" />
						<input type="file" name="fileText" id="fileTxt" />
						<label id="batchAddMsgBox"></label>
					</div>
				<div class="modal-footer">
						<button type="button" class="btn btn-primary" id="batchAdds" >确定</button>
				</div>
			</div>
			</form>
		</div>
	</div>
		<!-- 全局js -->
    <script src="${ctx}/js/jquery.min.js?v=2.1.4"></script>
    <script src="${ctx}/js/bootstrap.min.js?v=3.3.6"></script>
	<!-- 自定义js -->
	<script src="${ctx}/js/plugins/toastr/toastr.min.js"></script>
	<script	src="${ctx}/js/plugins/dataTables/jquery.dataTables.js"></script>
	<script	src="${ctx}/js/plugins/dataTables/dataTables.bootstrap.js"></script>
	<script type="text/javascript" src="${ctx}/js/jquery.validate.min.js"></script>
	<script src="${ctx}/js/ajaxfileupload.js"></script>
<script>
		toastr.options = {
		  "closeButton": false,
		  "debug": false,
		  "progressBar": false,
		  "positionClass": "toast-top-center",
		  "onclick": null,
		  "showDuration": "400",
		  "hideDuration": "1000",
		  "timeOut": "2000",
		  "extendedTimeOut": "1000",
		  "showEasing": "swing",
		  "hideEasing": "linear",
		  "showMethod": "fadeIn",
		  "hideMethod": "fadeOut"
		}

	$(document).ready(function() {
		
		var table = $('.dataTables-example').DataTable({
			"bPaginate":true,//翻页功能
			"bSort":false,//排序功能
			"iDisplayLength": 10,//每页显示的行数
			'bLengthChange': false, //是否允许用户自定义每页显示条数。
			"bProcessing": true, // 是否显示取数据时的那个等待提示
            "bServerSide": true,//这个用来指明是通过服务端来取数据
            "sAjaxSource": "${ctx}/couponManage/couponTableSearch",//这个是请求的地址
            "fnServerData": retrieveData, // 获取数据的处理函数
			"aoColumns": [
									{ "sClass": "center","bSearchable": true,"aTargets" : [0],
                                          "mRender": function(data, type, full) {
                                               return full.sequenceNumber;} 
                                     },
									 { "sClass": "center", "mRender": function(data, type, full) {
					 						if(full.coupon == null){
												return '';
											}else{
												return full.coupon;
											}
									}},
									{ "sClass": "center", "mRender": function(data, type, full) {
				 						if(full.pwd == null){
											return '';
										}else{
											return full.pwd;
										}
									}},
									{ "sClass": "center", "mRender": function(data, type, full) {
										if(full.status == 1){
											return '<span class="badge-primary">已领取</span>';
										}
										if(full.status==0){
											return "未领取";
										}
										return "";
									}},
									{ "sClass": "center", "mRender": function(data, type, full) {
										if(full.createTime == null){
											return '';
										}else{
											return full.createTime;
										}
									}},		
									{ "sClass": "center", "mRender": function(data, type, full) {
										if(full.drawTime == null){
											return '';
										}else{
											return full.drawTime;
										}
									}},									
									{ "sClass": "center", "mRender": function(data, type, full) {
										if(full.status == 1){
											return '<button class="btn btn-danger" onclick="showNoDelModal();">删除</button>';
										}
										if(full.status==0){
											return '<button class="btn btn-danger" onclick="showDelModal('+full.id+');">删除</button>';
										}
									}}
								]
		});	
		
		jQuery.validator.addMethod("alnum", function(value, element){
			return this.optional(element) ||/^[a-zA-Z0-9]+$/.test(value);
		}, "只能包括英文字母和数字");

		$("#addCoupon").click(function(){
			$("#addCouponForm").validate({
				rules:{
					couponname:{
						required:true,
						 alnum:".form-control"
					},
					pwd:{
						 alnum:".form-control"
					}
				},
				messages:{
					couponname:{
			            required:"卡券名不能为空"
					},
					pwd:{
					}
				},
				submitHandler:function(){
					$.ajax({
						type:"POST",
						url:"couponAdd",
						async: false,
						data:$("#addCouponForm").serialize(),
						error : function(msg) {
		    				toastr.error(msg.message);
		    			},
						success:function(data){
							if(data.msg.state == 0){
								//toastr.success(data.msg.message);
								window.location.reload();
							}else{
								toastr.error(data.msg.message);
							}
						}
					});
				}
			});
			$("#addCouponForm").attr('action','addCoupon');
			$("#addCouponForm").submit();
		});
		
		
		$("#adds").click(function() {
			var cid = $(this).data('cid');
			$("#addCouponId").attr("value", cid);
			$('#batchAddMsgBox').html('<span style="color:red">卡券与卡密请用“,”分隔,若无卡密则不需分隔。<br/>文件名示例：20160119(当前日期)_100(上传卡劵数量).txt</span>');
			$('#batchAdd').modal('show');
		});
		$("#batchAdds").click(function() {
			var pattern = /(\.*.txt$)/;
				if (!pattern.test($("#fileTxt").val())) {
					$('#batchAddMsgBox').html('<span style="color:red">批量导入卡券文件只支持TXT格式。</span>');
				}else{
						var formdata = new FormData($('#batchAddCoupon')[0]);
						$.ajax({  
	  	            		url:'couponBatchAdd',
	  	            		data: formdata,
		   	   		   	  type :"post",
		   	   		   	  processData: false,
		   	   		   	  contentType: false,  
	  	            		/* data:{"id":id},//附带上传的数据
	  	            		dataType: 'json', */
							success: function (result){
								$('#batchAddMsgBox').html('<span style="color:red">'+ result.message +'</span>');							
								if(result.state == 0){ 								
									window.location.reload();
								}
						},error: function(result){ 
							$('#batchAddMsgBox').html('<span style="color:red">Connection error!</span>');	
			            }
					});
				}
		});
	});
	
	//分页方法
	function retrieveData(sSource,aoData, fnCallback){
		var dataArr = eval("["+JSON.stringify(aoData)+"]");
		var giftId = "${giftId}";
		
		$.ajax({
            url : sSource, //这个就是请求地址对应sAjaxSource
            data : {"aoData":JSON.stringify(dataArr),"giftID":giftId},//这个是把datatable的一些基本数据传给后台,比如起始位置,每页显示的行数
            type : 'post',
            dataType : 'json',
            async : false,
            success : function(result) {
                fnCallback(result);//把返回的数据传给这个方法就可以了,datatable会自动绑定数据的
            },
            error : function(msg) {
            	alert('数据加载失败');
            }
        });
	}
	
	function showNoDelModal(){
		$('#noDelModal').modal("show");
	}
	
	function showDelModal(id){
		$('#delModal').modal("show");
		$("#delBtn").click(function() {
			$("#delCouponId").attr("value", id);
			//var path = "couponDel";
			//$('#delCoupon').attr("action", path).submit();
			$.ajax({
						type:"POST",
						url:"couponDel",
						async: false,
						data:$("#delCoupon").serialize(),
						error : function(msg) {
		    				toastr.error(msg.message);
		    			},
						success:function(data){
							if(data.msg.state == 0){
								//toastr.success(data.msg.message);
								window.location.reload();
							}else{
								toastr.error(data.msg.message);
							}
						}
					});
			$('#delModal').modal("hide");
		});
	}
	
</script>
</body>
</html>